package com.socialsoftware.api;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socialsoftware.model.Contact;
import com.socialsoftware.model.User;
import com.socialsoftware.util.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SNIHostName;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionSpec;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * API服务类，处理与服务器的网络请求
 */
public class ApiService {
    private static final String TAG = "ApiService";
    
    // 多个可能的API基础URL，应用将尝试按顺序连接
    private static final String[] API_URLS = {
        "https://192.168.125.43:8443",     // 本地开发服务器
        "https://api.socialsoftware.com",  // 生产服务器
        "https://dev-api.socialsoftware.com" // 开发服务器
    };
    
    // API端点常量
    private static final String API_PATH = "/api";
    private static final String AUTH_PATH = "/api/auth"; // 更新为正确的认证路径，与服务端匹配
    
    // 默认连接超时时间（秒）- 减少到更合理的值
    private static final int DEFAULT_TIMEOUT = 15;
    private static final int CONNECTION_TIMEOUT = 10;
    
    // 当前使用的API基础URL
    private String currentBaseUrl;
    private String currentApiUrl;
    private String currentAuthUrl;
    
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    private final OkHttpClient client;
    private final Gson gson;
    private final SessionManager sessionManager;
    private final Context appContext;
    
    // 保存上次成功连接的服务器URL，优先尝试
    private static String lastSuccessfulServer = null;
    
    /**
     * 创建支持SNI的SSLSocketFactory
     */
    private SSLSocketFactory createSniSocketFactory() {
        try {
            // 创建SSLContext，使用TLSv1.2
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            
            // 创建一个信任所有证书的TrustManager
            TrustManager[] trustManagers = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        Log.d(TAG, "SNI - 检查客户端证书信任: " + authType);
                        // 开发环境信任所有客户端证书
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        Log.d(TAG, "SNI - 检查服务器证书信任: " + authType);
                        // 开发环境信任所有服务器证书
                        if (chain != null && chain.length > 0) {
//                            Log.d(TAG, "SNI - 服务器证书信息: " + chain[0].getSubjectDN().getName());
                        }
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        Log.d(TAG, "SNI - 获取接受的发行者");
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
            };
            
            // 初始化SSLContext
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            
            // 获取基础的SSLSocketFactory
            SSLSocketFactory baseFactory = sslContext.getSocketFactory();
            
            // 创建并返回支持SNI的SSLSocketFactory包装类
            return new DelegatingSSLSocketFactory(baseFactory);
        } catch (Exception e) {
            Log.e(TAG, "创建SNI SocketFactory时出错", e);
            return null;
        }
    }
    
    /**
     * 支持SNI的SSLSocketFactory包装类
     * 确保所有Socket连接都启用了SNI扩展
     */
    private static class DelegatingSSLSocketFactory extends SSLSocketFactory {
        private final SSLSocketFactory delegate;
        
        public DelegatingSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }
        
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }
        
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }
        
        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
            Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
            return enableSNI(underlyingSocket, host);
        }
        
        @Override
        public Socket createSocket(String host, int port) throws IOException {
            Socket underlyingSocket = delegate.createSocket(host, port);
            return enableSNI(underlyingSocket, host);
        }
        
        @Override
        public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException {
            Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return enableSNI(underlyingSocket, host);
        }
        
        @Override
        public Socket createSocket(InetAddress host, int port) throws IOException {
            Socket underlyingSocket = delegate.createSocket(host, port);
            return enableSNI(underlyingSocket, host.getHostName());
        }
        
        @Override
        public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
            Socket underlyingSocket = delegate.createSocket(address, port, localAddress, localPort);
            return enableSNI(underlyingSocket, address.getHostName());
        }
        
        /**
         * 启用SNI扩展
         */
        private Socket enableSNI(Socket socket, String hostname) {
            if (socket instanceof SSLSocket) {
                SSLSocket sslSocket = (SSLSocket) socket;
                
                // 启用所有TLS协议版本
                sslSocket.setEnabledProtocols(new String[] {
                    "TLSv1",
                    "TLSv1.1",
                    "TLSv1.2",
                    "TLSv1.3"
                });
                
                // 设置SNI主机名 (通过SSLParameters)
                SSLParameters sslParameters = sslSocket.getSSLParameters();
                sslParameters.setServerNames(Arrays.asList(new SNIHostName(hostname)));
                sslSocket.setSSLParameters(sslParameters);
            }
            return socket;
        }
    }
    
    public ApiService(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
        this.appContext = sessionManager.getContext();
        
        // 配置OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        
        // 添加认证拦截器
        builder.addInterceptor(new AuthInterceptor(sessionManager));
        
        // 允许所有TLS版本
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .allEnabledTlsVersions()
                .allEnabledCipherSuites()
                .build();
        builder.connectionSpecs(Arrays.asList(spec, ConnectionSpec.CLEARTEXT));
        
        // 配置SSL和SNI支持
        try {
            // 创建一个信任所有证书的TrustManager - 注意：这仅应在开发环境中使用
            final X509TrustManager trustAllCertificates = new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    Log.d(TAG, "SSL - 信任所有客户端证书: " + authType);
                    // 不验证，信任所有
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
//                    Log.d(TAG, "SSL - 信任所有服务器证书: " + authType);
                    if (chain != null && chain.length > 0) {
//                        Log.d(TAG, "SSL - 服务器证书信息: " + chain[0].getSubjectDN().getName());
                    }
                    // 不验证，信任所有
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                    Log.d(TAG, "SSL - 返回空的信任证书列表");
                    return new java.security.cert.X509Certificate[0]; // 必须返回空数组而不是null
                }
            };

            // 创建一个SSL上下文，信任所有证书
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { trustAllCertificates }, new java.security.SecureRandom());
            
            // 创建支持SNI的SSLSocketFactory
            SSLSocketFactory sslSocketFactory = new DelegatingSSLSocketFactory(sslContext.getSocketFactory());
            
            // 设置OkHttpClient使用我们的SSLSocketFactory和TrustManager
            builder.sslSocketFactory(sslSocketFactory, trustAllCertificates);

            // 允许所有主机名，禁用主机名验证
            builder.hostnameVerifier((hostname, session) -> {
                Log.d(TAG, "验证主机名: " + hostname + " 与SSL会话: " + session.getPeerHost());
                return true; // 警告：这会禁用主机名验证，仅用于开发环境
            });
            
//            Log.d(TAG, "已配置为信任所有SSL证书（仅用于开发环境）");
        } catch (Exception e) {
            Log.e(TAG, "配置SSL信任管理器时出错", e);
        }
                
        this.client = builder.build();
        this.gson = new Gson();
        
        // 优先使用上次成功的服务器
        if (lastSuccessfulServer != null) {
            currentBaseUrl = lastSuccessfulServer;
            currentApiUrl = currentBaseUrl + API_PATH;
            currentAuthUrl = currentBaseUrl + AUTH_PATH;
            Log.d(TAG, "使用上次成功连接的服务器: " + currentBaseUrl);
        } else {
            // 默认使用第一个URL
            currentBaseUrl = API_URLS[0];
            currentApiUrl = currentBaseUrl + API_PATH;
            currentAuthUrl = currentBaseUrl + AUTH_PATH;
        }
        
        Log.d(TAG, "ApiService初始化完成，基础URL: " + currentBaseUrl);
        
        // 在后台线程中测试连接
        new Thread(() -> {
            findWorkingApiServer();
        }).start();
    }
    
    /**
     * 尝试连接到可用的API服务器
     */
    private void findWorkingApiServer() {
        if (!isNetworkAvailable()) {
            Log.w(TAG, "没有可用的网络连接");
            return;
        }
        
        boolean foundWorking = false;
        
        // 首先检查上次成功的服务器
        if (lastSuccessfulServer != null) {
            if (isServerReachable(lastSuccessfulServer)) {
                currentBaseUrl = lastSuccessfulServer;
                currentApiUrl = currentBaseUrl + API_PATH;
                currentAuthUrl = currentBaseUrl + AUTH_PATH;
                foundWorking = true;
                Log.d(TAG, "上次成功的API服务器仍然可用: " + currentBaseUrl);
                return;
            } else {
                Log.d(TAG, "上次成功的API服务器不再可用: " + lastSuccessfulServer);
            }
        }
        
        // 尝试其他服务器
        for (String baseUrl : API_URLS) {
            if (isServerReachable(baseUrl)) {
                currentBaseUrl = baseUrl;
                currentApiUrl = currentBaseUrl + API_PATH;
                currentAuthUrl = currentBaseUrl + AUTH_PATH;
                lastSuccessfulServer = baseUrl; // 保存成功的服务器
                foundWorking = true;
//                Log.d(TAG, "找到可用的API服务器: " + currentBaseUrl);
                
                // 验证API路径是否真的可用
                verifyApiPath(baseUrl);
                break;
            }
        }
        
        if (!foundWorking) {
            Log.w(TAG, "所有API服务器都无法连接，使用默认URL: " + currentBaseUrl);
        }
    }
    
    /**
     * 验证API路径是否可用
     */
    private void verifyApiPath(String baseUrl) {
        // 验证API路径是否可用
        Request request = new Request.Builder()
                .url(baseUrl + "/health")  // 大多数API服务器提供健康检查端点
                .get()
                .build();
                
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "API健康检查失败: " + e.getMessage());
                // 即使健康检查失败也继续使用该服务器
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "API健康检查成功，服务器正常运行");
                } else {
//                    Log.d(TAG, "API健康检查返回非成功状态码: " + response.code());
                }
                response.close();
            }
        });
    }
    
    /**
     * 检查是否有网络连接
     */
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
                appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    
    /**
     * 检查服务器是否可达
     */
    private boolean isServerReachable(String baseUrl) {
        try {
            // 从URL中提取主机和端口
            HttpUrl url = HttpUrl.parse(baseUrl);
            if (url == null) {
                Log.e(TAG, "无效的URL: " + baseUrl);
                return false;
            }
            
            String host = url.host();
            int port = url.port();
            if (port == -1) {
                port = baseUrl.startsWith("https") ? 443 : 80;
            }
            
            // 首先尝试OkHttp ping请求，更好地处理SSL和代理
            Request request = new Request.Builder()
                    .url(baseUrl)
                    .head()  // 只请求头信息，减少数据传输
                    .build();
                    
            try {
                Response response = client.newCall(request).execute();
                boolean isReachable = response.isSuccessful() || response.code() == 404;  // 404表示服务器在线但路径不存在
                response.close();
                if (isReachable) {
//                    Log.d(TAG, "服务器 " + baseUrl + " 可以通过HTTP请求访问");
                    return true;
                }
            } catch (IOException e) {
                Log.d(TAG, "HTTP请求 " + baseUrl + " 失败: " + e.getMessage() + "，尝试套接字连接");
            }
            
            // 如果HTTP请求失败，尝试套接字连接
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), 3000); // 3秒超时
            socket.close();
            Log.d(TAG, "服务器 " + baseUrl + " 可以通过套接字连接访问");
            return true;
        } catch (Exception e) {
            Log.d(TAG, "服务器 " + baseUrl + " 不可达: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param callback 回调接口，用于返回结果
     */
    public void login(String username, String password, final ApiCallback<Map<String, Object>> callback) {
        Log.d(TAG, "开始登录请求，用户名: " + username);
        
        if (!isNetworkAvailable()) {
            Log.e(TAG, "无网络连接，无法登录");
            callback.onFailure(new ApiError(0, "无网络连接，请检查网络设置"));
            return;
        }
        
        // 构建请求体
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("username", username);
        requestMap.put("password", password);
        String requestJson = gson.toJson(requestMap);
        
        RequestBody requestBody = RequestBody.create(JSON, requestJson);
        
        // 构建请求
        String url = currentBaseUrl + "/api/auth/login";
        Log.d(TAG, "登录请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "登录网络请求失败: " + e.getMessage(), e);
                
                // 提供更详细的错误信息，特别是SSL相关错误
                String errorMessage = e.getMessage();
                int errorCode = 500;
                
                if (errorMessage != null) {
                    if (errorMessage.contains("TLSV1_ALERT") || 
                        errorMessage.contains("SSL") || 
                        errorMessage.contains("certificate") ||
                        errorMessage.contains("handshake")) {
                        Log.e(TAG, "SSL连接错误: " + errorMessage, e);
                        errorCode = 495; // SSL证书错误
                        errorMessage = "SSL连接错误: " + errorMessage;
                    } else if (errorMessage.contains("ECONNREFUSED") || 
                             errorMessage.contains("failed to connect")) {
                        errorCode = 502; // 连接被拒绝
                    } else if (errorMessage.contains("timeout")) {
                        errorCode = 504; // 超时
                    }
                }
                
                callback.onFailure(new ApiError(errorCode, "网络请求失败: " + errorMessage));
                
                // 尝试重新查找可用服务器
                findWorkingApiServer();
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "登录成功，响应: " + responseBody);
                    
                    Map<String, Object> responseMap = gson.fromJson(responseBody, new TypeToken<Map<String, Object>>(){}.getType());
                    
                    // 返回结果
                    callback.onSuccess(responseMap);
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理登录响应时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 用户注册
     * @param registerData 注册数据
     * @param callback 回调接口，用于返回结果
     */
    public void register(Map<String, Object> registerData, final ApiCallback<Map<String, Object>> callback) {
        Log.d(TAG, "开始注册请求，用户名: " + registerData.get("username"));
        
        if (!isNetworkAvailable()) {
            Log.e(TAG, "无网络连接，无法注册");
            callback.onFailure(new ApiError(0, "无网络连接，请检查网络设置"));
            return;
        }
        
        // 构建请求体
        String requestJson = gson.toJson(registerData);
        RequestBody requestBody = RequestBody.create(JSON, requestJson);
        
        // 构建请求
        String url = currentBaseUrl + "/api/auth/register";
        Log.d(TAG, "注册请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "注册网络请求失败: " + e.getMessage(), e);
                
                // 提供更详细的错误信息，特别是SSL相关错误
                String errorMessage = e.getMessage();
                int errorCode = 500;
                
                if (errorMessage != null) {
                    if (errorMessage.contains("TLSV1_ALERT") || 
                        errorMessage.contains("SSL") || 
                        errorMessage.contains("certificate") ||
                        errorMessage.contains("handshake")) {
                        Log.e(TAG, "SSL连接错误: " + errorMessage, e);
                        errorCode = 495; // SSL证书错误
                        errorMessage = "SSL连接错误: " + errorMessage;
                    } else if (errorMessage.contains("ECONNREFUSED") || 
                             errorMessage.contains("failed to connect")) {
                        errorCode = 502; // 连接被拒绝
                    } else if (errorMessage.contains("timeout")) {
                        errorCode = 504; // 超时
                    }
                }
                
                callback.onFailure(new ApiError(errorCode, "网络请求失败: " + errorMessage));
                
                // 尝试重新查找可用服务器
                findWorkingApiServer();
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "注册响应码: " + response.code() + ", 响应: " + responseBody);
                    
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        
                        // 尝试解析错误信息
                        try {
                            JSONObject errorJson = new JSONObject(responseBody);
                            if (errorJson.has("message")) {
                                errorMessage = errorJson.getString("message");
                            } else if (errorJson.has("error")) {
                                errorMessage = errorJson.getString("error");
                            }
                        } catch (JSONException e) {
                            // 如果不是JSON格式，使用原始响应
                            if (!responseBody.isEmpty()) {
                                errorMessage += " - " + responseBody;
                            }
                        }
                        
                        Log.e(TAG, errorMessage);
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        return;
                    }
                    
                    // 解析响应
                    Log.d(TAG, "注册成功，响应: " + responseBody);
                    
                    try {
                        // 处理嵌套的JSON结构
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        Map<String, Object> responseMap;
                        
                        if (jsonResponse.has("data") && !jsonResponse.isNull("data")) {
                            // 新API格式: { "status": 200, "message": "...", "data": { ... } }
                            JSONObject data = jsonResponse.getJSONObject("data");
                            responseMap = gson.fromJson(data.toString(), new TypeToken<Map<String, Object>>(){}.getType());
                        } else {
                            // 旧API格式: { ... }
                            responseMap = gson.fromJson(responseBody, new TypeToken<Map<String, Object>>(){}.getType());
                        }
                        
                        // 返回结果
                        callback.onSuccess(responseMap);
                    } catch (JSONException e) {
                        Log.e(TAG, "解析注册响应时发生JSON错误", e);
                        callback.onFailure(new ApiError(500, "解析响应数据失败: " + e.getMessage()));
                    }
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理注册响应时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 检查用户名是否存在
     * @param username 用户名
     * @param callback 回调接口，用于返回结果
     */
    public void checkUsernameExists(String username, final ApiCallback<Boolean> callback) {
        Log.d(TAG, "开始检查用户名是否存在: " + username);
        
        if (!isNetworkAvailable()) {
            Log.e(TAG, "无网络连接，无法检查用户名");
            callback.onFailure(new ApiError(0, "无网络连接，请检查网络设置"));
            return;
        }
        
        // 构建请求URL - 使用正确的API路径
        HttpUrl url = HttpUrl.parse(currentBaseUrl + "/api/users/check/username").newBuilder()
                .addQueryParameter("value", username)
                .build();
        
        Log.d(TAG, "请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "检查用户名网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
                
                // 尝试重新查找可用服务器
                findWorkingApiServer();
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "检查用户名成功，响应: " + responseBody);
                    
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    // 处理嵌套的JSON结构
                    boolean exists;
                    if (jsonResponse.has("data") && !jsonResponse.isNull("data")) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        exists = data.getBoolean("exists");
                    } else if (jsonResponse.has("exists")) {
                        // 兼容旧的API格式
                        exists = jsonResponse.getBoolean("exists");
                    } else {
                        // 如果找不到exists字段，默认为false
                        Log.w(TAG, "响应中没有找到exists字段，默认为false");
                        exists = false;
                    }
                    
                    // 返回结果
                    callback.onSuccess(exists);
                    
                } catch (JSONException e) {
                    Log.e(TAG, "解析用户名检查结果失败", e);
                    callback.onFailure(new ApiError(500, "解析数据失败: " + e.getMessage()));
                } catch (Exception e) {
                    Log.e(TAG, "处理用户名检查结果时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 检查邮箱是否存在
     * @param email 邮箱
     * @param callback 回调接口，用于返回结果
     */
    public void checkEmailExists(String email, final ApiCallback<Boolean> callback) {
        Log.d(TAG, "开始检查邮箱是否存在: " + email);
        
        // 构建请求URL
        HttpUrl url = HttpUrl.parse(currentApiUrl + "/users/check/email").newBuilder()
                .addQueryParameter("value", email)
                .build();
        
        Log.d(TAG, "请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "检查邮箱网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "检查邮箱成功，响应: " + responseBody);
                    
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    // 处理嵌套的JSON结构
                    boolean exists;
                    if (jsonResponse.has("data") && !jsonResponse.isNull("data")) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        exists = data.getBoolean("exists");
                    } else if (jsonResponse.has("exists")) {
                        // 兼容旧的API格式
                        exists = jsonResponse.getBoolean("exists");
                    } else {
                        // 如果找不到exists字段，默认为false
                        Log.w(TAG, "响应中没有找到exists字段，默认为false");
                        exists = false;
                    }
                    
                    // 返回结果
                    callback.onSuccess(exists);
                    
                } catch (JSONException e) {
                    Log.e(TAG, "解析邮箱检查结果失败", e);
                    callback.onFailure(new ApiError(500, "解析数据失败: " + e.getMessage()));
                } catch (Exception e) {
                    Log.e(TAG, "处理邮箱检查结果时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 获取联系人列表
     * @param callback 回调接口，用于返回结果
     */
    public void getContacts(final ApiCallback<List<Contact>> callback) {
        Log.d(TAG, "开始从服务器获取联系人列表");
        
        // 检查是否已登录
        if (!sessionManager.isLoggedIn()) {
            Log.e(TAG, "获取联系人失败：用户未登录");
            callback.onFailure(new ApiError(401, "用户未登录"));
            return;
        }
        
        if (!isNetworkAvailable()) {
            Log.e(TAG, "无网络连接，无法获取联系人");
            callback.onFailure(new ApiError(0, "无网络连接，请检查网络设置"));
            return;
        }
        
        // 获取认证令牌
        String authToken = sessionManager.getAuthToken();
        if (authToken == null) {
            Log.e(TAG, "获取联系人失败：无效的认证令牌");
            callback.onFailure(new ApiError(401, "无效的认证令牌"));
            return;
        }
        
        // 构建请求
        String url = currentApiUrl + "/contacts";
        Log.d(TAG, "请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + authToken)
                .get()
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取联系人网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
                
                // 尝试重新查找可用服务器
                findWorkingApiServer();
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "获取联系人成功，响应: " + responseBody);
                    
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    // 首先获取data字段
                    JSONObject dataObject = jsonResponse.getJSONObject("data");
                    JSONArray contactsArray = dataObject.getJSONArray("contacts");
                    
                    Type contactListType = new TypeToken<List<Contact>>(){}.getType();
                    List<Contact> contacts = gson.fromJson(contactsArray.toString(), contactListType);
                    System.out.println("APIService              "+contacts);
                    // 返回结果
                    callback.onSuccess(contacts);
                    
                } catch (JSONException e) {
                    Log.e(TAG, "解析联系人数据失败", e);
                    callback.onFailure(new ApiError(500, "解析数据失败: " + e.getMessage()));
                } catch (Exception e) {
                    Log.e(TAG, "处理联系人数据时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 搜索好友
     * @param query 搜索关键词
     * @param searchType 搜索类型（微信号/手机号/邮箱/qrcode）
     * @param callback 回调接口，用于返回结果
     */
    public void searchFriends(String query, String searchType, final ApiCallback<List<Contact>> callback) {
        Log.d(TAG, "开始搜索好友: " + query + ", 类型: " + searchType);
        
        // 检查是否已登录
        if (!sessionManager.isLoggedIn() && !"qrcode".equals(searchType)) {
            Log.e(TAG, "搜索好友失败：用户未登录");
            callback.onFailure(new ApiError(401, "用户未登录"));
            return;
        }
        
        // 获取认证令牌 - 对于二维码扫描，可以不需要认证令牌
        String authToken = null;
        if (sessionManager != null) {
            authToken = sessionManager.getAuthToken();
        }
        
        if (authToken == null && !"qrcode".equals(searchType)) {
            Log.e(TAG, "搜索好友失败：无效的认证令牌");
            callback.onFailure(new ApiError(401, "无效的认证令牌"));
            return;
        }
        
        // 构建请求URL
        HttpUrl.Builder urlBuilder = HttpUrl.parse(currentApiUrl != null ? 
                currentApiUrl + "/search/friends" : 
                "https://api.socialsoftware.com/api/search/friends").newBuilder()
                .addQueryParameter("query", query)
                .addQueryParameter("type", searchType);
        
        HttpUrl url = urlBuilder.build();
        Log.d(TAG, "请求URL: " + url);
        
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .get();
        
        // 如果有认证令牌，添加到请求头
        if (authToken != null) {
            requestBuilder.header("Authorization", "Bearer " + authToken);
        }
        
        Request request = requestBuilder.build();
        
        // 如果客户端未初始化，创建一个新的客户端
        OkHttpClient httpClient = client != null ? client : new OkHttpClient.Builder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build();
        
        // 执行异步请求
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "搜索好友网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "搜索好友成功，响应: " + responseBody);
                    
                    // 从JSON响应中提取数据
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    JSONArray dataArray;
                    
                    // 获取data字段并确保它是数组类型
                    Object dataObj = jsonResponse.get("data");
                    if (dataObj instanceof JSONArray) {
                        dataArray = (JSONArray) dataObj;
                    } else if (dataObj.toString().equals("[]")) {
                        // 处理空数组字符串情况
                        dataArray = new JSONArray();
                    } else if (dataObj instanceof JSONObject) {
                        // 如果data是对象类型，尝试获取内部结果数组
                        JSONObject dataObject = (JSONObject) dataObj;
                        if (dataObject.has("results")) {
                            dataArray = dataObject.getJSONArray("results");
                        } else {
                            // 没有results字段，创建空数组
                            dataArray = new JSONArray();
                        }
                    } else {
                        // 其他情况创建空数组
                        dataArray = new JSONArray();
                    }
                    
                    // 将JSONArray转换为Contact列表
                    List<Contact> results = new ArrayList<>();
                    if (dataArray.length() > 0) {
                        // 手动解析JSON数组，确保设置正确的用户名
                        for (int i = 0; i < dataArray.length(); i++) {
                            try {
                                JSONObject userObj = dataArray.getJSONObject(i);
                                String id = userObj.optString("id", "");
                                String username = userObj.optString("username", "");
                                String fullName = userObj.optString("fullName", "");
                                String avatarUrl = userObj.optString("avatarUrl", "");
                                String region = userObj.optString("region", "未知地区");
                                
//                                // 确保name字段不为空，优先使用fullName，其次使用username
//                                String name = !TextUtils.isEmpty(fullName) ? fullName : username;
//
//                                // 如果name仍然为空，使用id作为备用
//                                if (TextUtils.isEmpty(name)) {
//                                    name = id;
//                                }
                                
//                                Contact contact = new Contact(id, name, avatarUrl != null ? avatarUrl : "avatar_default");
                                Contact contact=new Contact();
                                contact.setRemark(fullName);
                                contact.setName(username);
                                contact.setId(id);
                                contact.setAvatar("mouren");
                                contact.setRegion(region);
                                
                                // 设置额外的用户名字段，用于显示账号
//                                if (!TextUtils.isEmpty(username)) {
//                                    contact.setRemark(username); // 临时用remark字段保存username
//                                }
                                results.add(contact);
                                Log.d(TAG, "解析到联系人: " + contact);
                            } catch (JSONException e) {
                                Log.e(TAG, "解析联系人JSON对象失败", e);
                            }
                        }
                    } else if ("qrcode".equals(searchType)) {
                        // 如果是二维码搜索且没有结果，创建一个模拟联系人用于测试
                        Contact mockContact = new Contact(query, query, "avatar_default");
                        mockContact.setRegion("未知地区");
                        mockContact.setRemark(query); // 设置用户名为查询值
                        results.add(mockContact);
                    }
                    
                    // 返回结果
                    callback.onSuccess(results);
                    
                } catch (JSONException e) {
                    Log.e(TAG, "解析搜索结果失败", e);
                    callback.onFailure(new ApiError(500, "解析数据失败: " + e.getMessage()));
                } catch (Exception e) {
                    Log.e(TAG, "处理搜索结果时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 刷新认证令牌
     * @param refreshToken 用于刷新的令牌
     * @param callback 回调接口，用于返回结果
     */
    public void refreshToken(String refreshToken, final ApiCallback<Map<String, Object>> callback) {
        Log.d(TAG, "开始刷新认证令牌");
        
        if (!isNetworkAvailable()) {
            Log.e(TAG, "无网络连接，无法刷新令牌");
            callback.onFailure(new ApiError(0, "无网络连接，请检查网络设置"));
            return;
        }
        
        // 构建请求体
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("refreshToken", refreshToken);
        String requestJson = gson.toJson(requestMap);
        
        RequestBody requestBody = RequestBody.create(JSON, requestJson);
        
        // 构建请求
        String url = currentAuthUrl + "/refresh-token";
        Log.d(TAG, "刷新令牌请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .tag("token_refresh") // 标记为令牌刷新请求
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "刷新令牌网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
                
                // 尝试重新查找可用服务器
                findWorkingApiServer();
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        // 处理HTTP错误
                        int statusCode = response.code();
                        String errorMessage = "服务器返回错误: " + statusCode;
                        Log.e(TAG, errorMessage + " - " + response.message());
                        callback.onFailure(new ApiError(statusCode, errorMessage));
                        response.close();
                        return;
                    }
                    
                    // 解析响应
                    String responseBody = response.body().string();
                    response.close();
                    Log.d(TAG, "刷新令牌成功，响应: " + responseBody);
                    
                    Map<String, Object> responseMap = gson.fromJson(responseBody, new TypeToken<Map<String, Object>>(){}.getType());
                    
                    // 返回结果
                    callback.onSuccess(responseMap);
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理刷新令牌响应时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 获取当前使用的API基础URL
     * @return 当前API基础URL
     */
    public String getCurrentBaseUrl() {
        return currentBaseUrl;
    }
    
    /**
     * 获取OkHttpClient实例
     * @return 配置好的OkHttpClient实例
     */
    public OkHttpClient getHttpClient() {
        return client;
    }
    
    /**
     * 登出用户
     * @param callback 回调接口，用于返回结果
     */
    public void logout(final ApiCallback<Boolean> callback) {
        Log.d(TAG, "开始发送登出请求");
        
        // 检查是否已登录
        if (!sessionManager.isLoggedIn()) {
            Log.d(TAG, "用户已处于登出状态，无需发送请求");
            callback.onSuccess(true);
            return;
        }
        
        if (!isNetworkAvailable()) {
            Log.w(TAG, "无网络连接，无法发送登出请求，直接清除本地会话");
            sessionManager.logout();
            callback.onSuccess(true);
            return;
        }
        
        // 构建请求
        String url = currentAuthUrl + "/logout";
        Log.d(TAG, "登出请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON, "{}"))
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "登出网络请求失败: " + e.getMessage(), e);
                // 即使请求失败，也应该清除本地会话
                sessionManager.logout();
                callback.onSuccess(true);
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 无论服务器响应如何，都应该清除本地会话
                sessionManager.logout();
                callback.onSuccess(true);
                Log.d(TAG, "用户已登出");
            }
        });
    }

    /**
     * API回调接口
     * @param <T> 返回数据的类型
     */
    public interface ApiCallback<T> {
        void onSuccess(T data);
        void onFailure(ApiError error);
    }

    /**
     * 发送好友请求
     * @param requestData 请求数据
     * @param callback 回调接口，用于返回结果
     */
    public void sendFriendRequest(Map<String, Object> requestData, final ApiCallback<Map<String, Object>> callback) {
        Log.d(TAG, "开始发送好友请求");
        
        // 检查是否已登录
        if (!sessionManager.isLoggedIn()) {
            Log.e(TAG, "发送好友请求失败：用户未登录");
            callback.onFailure(new ApiError(401, "用户未登录"));
            return;
        }
        
        // 获取认证令牌
        String authToken = sessionManager.getAuthToken();
        if (authToken == null) {
            Log.e(TAG, "发送好友请求失败：无效的认证令牌");
            callback.onFailure(new ApiError(401, "无效的认证令牌"));
            return;
        }
        
        // 输出请求数据，便于调试
        Log.d(TAG, "好友请求数据: " + new Gson().toJson(requestData));
        
        // 构建请求
        String url = currentApiUrl + "/friendships/mobile";
        Log.d(TAG, "好友请求URL: " + url);
        System.out.println(url);
        
        RequestBody requestBody = RequestBody.create(
                JSON, new Gson().toJson(requestData));
        
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + authToken)
                .post(requestBody)
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "发送好友请求网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseBody = response.body().string();
                    Log.d(TAG, "好友请求响应: " + responseBody);
                    
                    if (!response.isSuccessful()) {
                        // 尝试从错误响应中提取有用信息
                        String errorMessage = "发送好友请求失败: " + response.code();
                        try {
                            JSONObject errorJson = new JSONObject(responseBody);
                            if (errorJson.has("error")) {
                                errorMessage += " - " + errorJson.getString("error");
                            }
                            if (errorJson.has("message")) {
                                errorMessage += ": " + errorJson.getString("message");
                            }
                        } catch (JSONException e) {
                            // 如果响应不是JSON格式，使用原始响应
                            if (!responseBody.isEmpty()) {
                                errorMessage += " - " + responseBody;
                            }
                        }
                        
                        callback.onFailure(new ApiError(response.code(), errorMessage));
                        return;
                    }
                    
                    // 解析成功响应
                    Map<String, Object> responseMap;
                    try {
                        // 尝试解析JSON响应
                        responseMap = gson.fromJson(responseBody, new TypeToken<Map<String, Object>>(){}.getType());
                    } catch (Exception e) {
                        // 如果无法解析为Map，创建一个包含原始响应的Map
                        responseMap = new HashMap<>();
                        responseMap.put("rawResponse", responseBody);
                        responseMap.put("success", true);
                    }
                    
                    // 返回结果
                    callback.onSuccess(responseMap);
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理好友请求响应时发生错误", e);
                    callback.onFailure(new ApiError(500, "处理响应数据时发生错误: " + e.getMessage()));
                }
            }
        });
    }

    /**
     * 获取当前用户的好友列表
     * @param callback 回调处理结果
     */
    public void getFriends(final ApiCallback<List<Contact>> callback) {
        // 检查认证状态
        if (!sessionManager.isLoggedIn()) {
            callback.onFailure(new ApiError(401, "未登录，无法获取好友列表"));
            return;
        }
        
        String token = sessionManager.getAuthToken();
        if (token == null || token.isEmpty()) {
            callback.onFailure(new ApiError(401, "无效的认证令牌"));
            return;
        }
        
        // 构建API请求URL
        String url = currentBaseUrl + "/api/friendships/accepted/current";
        
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + token)
                .get()
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取好友列表失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(0, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, "获取好友列表失败: HTTP " + response.code());
                    callback.onFailure(new ApiError(response.code(), "服务器响应错误: " + response.code()));
                    return;
                }
                
                try {
                    String responseBody = response.body().string();
                    Log.d(TAG, "获取好友列表成功: " + responseBody);
                    
                    // 解析JSON响应
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
                    List<Map<String, Object>> friendsData = gson.fromJson(responseBody, listType);
                    
                    // 转换为Contact对象
                    List<Contact> contacts = new ArrayList<>();
                    for (Map<String, Object> friendData : friendsData) {
                        Contact contact = parseContactFromFriendship(friendData);
                        if (contact != null) {
                            contacts.add(contact);
                        }
                    }
                    
                    Log.d(TAG, "解析到 " + contacts.size() + " 个好友");
                    callback.onSuccess(contacts);
                } catch (Exception e) {
                    Log.e(TAG, "解析好友列表数据失败: " + e.getMessage(), e);
                    callback.onFailure(new ApiError(0, "解析数据失败: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 从好友关系数据中解析联系人信息
     * @param friendshipData 好友关系数据
     * @return 联系人对象
     */
    private Contact parseContactFromFriendship(Map<String, Object> friendshipData) {
        try {
            // 获取当前用户ID
            Long currentUserId = sessionManager.getCurrentUserId();
            if (currentUserId == null) {
                Log.e(TAG, "无法获取当前用户ID");
                return null;
            }
            
            // 从好友关系中提取好友信息（非当前用户的一方）
            Map<String, Object> userMap;
            
            // 检查requester和addressee，确定哪一个是好友
            if (friendshipData.containsKey("requester") && friendshipData.containsKey("addressee")) {
                Map<String, Object> requester = (Map<String, Object>) friendshipData.get("requester");
                Map<String, Object> addressee = (Map<String, Object>) friendshipData.get("addressee");
                
                // 获取requester和addressee的ID
                Object requesterId = requester.get("id");
                Object addresseeId = addressee.get("id");
                
                // 比较ID，确定哪一个是好友
                boolean isRequesterCurrentUser = false;
                if (requesterId instanceof Number) {
                    isRequesterCurrentUser = ((Number) requesterId).longValue() == currentUserId;
                } else if (requesterId != null) {
                    isRequesterCurrentUser = requesterId.toString().equals(currentUserId.toString());
                }
                
                // 选择非当前用户的一方作为联系人
                userMap = isRequesterCurrentUser ? addressee : requester;
            } else {
                Log.e(TAG, "好友关系数据格式无效");
                return null;
            }
            
            // 提取基本信息
            String id = extractStringValue(userMap, "id");
            String name = extractStringValue(userMap, "fullName");
            if (name == null || name.isEmpty()) {
                name = extractStringValue(userMap, "username");
            }
            
            // 提取头像URL
            String avatarUrl = extractStringValue(userMap, "avatarUrl");
            String avatar = "avatar_default"; // 默认头像
            
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                // 从URL中提取文件名作为资源名
                if (avatarUrl.contains("/")) {
                    String[] parts = avatarUrl.split("/");
                    String fileName = parts[parts.length - 1];
                    // 移除文件扩展名
                    int dotIndex = fileName.lastIndexOf(".");
                    if (dotIndex > 0) {
                        fileName = fileName.substring(0, dotIndex);
                    }
                    avatar = fileName;
                } else {
                    avatar = avatarUrl;
                }
            }
            
            // 创建联系人对象
            Contact contact = new Contact(id, name, avatar);
            
            // 设置额外信息
            contact.setRegion(extractStringValue(userMap, "region"));
            
            // 设置备注名（如果存在）
            if (friendshipData.containsKey("remark")) {
                contact.setRemark(extractStringValue(friendshipData, "remark"));
            }
            
            return contact;
        } catch (Exception e) {
            Log.e(TAG, "解析好友数据失败: " + e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 安全地从Map中提取字符串值
     */
    private String extractStringValue(Map<String, Object> map, String key) {
        if (map == null || !map.containsKey(key) || map.get(key) == null) {
            return null;
        }
        return map.get(key).toString();
    }

    /**
     * 检查与指定用户的好友关系状态
     * @param targetUserId 目标用户ID
     * @param callback 回调接口，返回关系状态码：
     *                0 - 没有关系
     *                1 - 已经是好友
     *                2 - 已发送请求，等待确认
     *                3 - 对方发送了请求给你
     */
    public void checkFriendshipStatus(String targetUserId, final ApiCallback<Integer> callback) {
        Log.d(TAG, "开始检查好友关系状态，目标用户ID: " + targetUserId);
        
        // 检查是否已登录
        if (!sessionManager.isLoggedIn()) {
            Log.e(TAG, "检查好友关系失败：用户未登录");
            callback.onFailure(new ApiError(401, "用户未登录"));
            return;
        }
        
        // 获取当前用户ID
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Log.e(TAG, "检查好友关系失败：无法获取当前用户ID");
            callback.onFailure(new ApiError(401, "无法获取当前用户ID"));
            return;
        }
        
        // 获取认证令牌
        String authToken = sessionManager.getAuthToken();
        if (authToken == null) {
            Log.e(TAG, "检查好友关系失败：无效的认证令牌");
            callback.onFailure(new ApiError(401, "无效的认证令牌"));
            return;
        }
        
        // 构建请求URL
        HttpUrl url = HttpUrl.parse(currentApiUrl + "/friendships/status").newBuilder()
                .addQueryParameter("userId", targetUserId)
                .build();
        
        Log.d(TAG, "请求URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + authToken)
                .get()
                .build();
        
        // 执行异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "检查好友关系网络请求失败: " + e.getMessage(), e);
                callback.onFailure(new ApiError(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseBody = response.body().string();
                    Log.d(TAG, "好友关系状态响应: " + responseBody);
                    
                    if (!response.isSuccessful()) {
                        // 如果API尚未实现，返回默认状态0（没有关系）
                        if (response.code() == 404) {
                            Log.w(TAG, "好友关系状态API未实现，默认返回没有关系");
                            callback.onSuccess(0);
                            return;
                        }
                        
                        callback.onFailure(new ApiError(response.code(), "服务器返回错误: " + response.code()));
                        return;
                    }
                    
                    // 解析响应
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    // 获取状态码
                    int status;
                    if (jsonResponse.has("data") && !jsonResponse.isNull("data")) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        status = data.getInt("status");
                    } else if (jsonResponse.has("status")) {
                        status = jsonResponse.getInt("status");
                    } else {
                        // 如果找不到状态字段，默认为0（没有关系）
                        status = 0;
                    }
                    
                    // 返回结果
                    callback.onSuccess(status);
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理好友关系状态响应时发生错误", e);
                    
                    // 如果解析失败，默认返回0（没有关系）
                    callback.onSuccess(0);
                }
            }
        });
    }
}